package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;

import dto.DataManager;

/**
 * Servlet implementation class Card
 */
@WebServlet("/Card")
public class Card extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
   
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  response.setContentType("text/html;charset=UTF-8");  
		PrintWriter out = response.getWriter();
		DataManager dataManager = new DataManager();
		String username = (String) request.getSession().getAttribute("username");
		User user = dataManager.getUserWithUserName(username);
		int cardId = request.getParameter("cardId")==null? -1: Integer.parseInt(request.getParameter("cardId"));
		System.out.println(cardId);
		if(cardId != -1)
		{
			int money = dataManager.getMoneyByCardId(cardId);
			if(money != -1)
			{
				dataManager.updateMoney(user.getUserId(), money+user.getOwnMoney());
				dataManager.updateStatusCard(cardId);
				//out.print(""+user.getOwnMoney()+"");
				out.print(user.getOwnMoney()+money);
				
			}
			else
			{
				//out.print(""+user.getOwnMoney()+"");
				out.print("false");
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
